import React, { useState } from 'react';
import { Table, TableProps } from 'antd';
import { Resizable } from 'react-resizable';
import { BaseColumn } from './columns';
import './BaseTable.css';

// 可调整大小的表头
const ResizableTitle = (props) => {
  const { onResize, width, ...restProps } = props;

  if (!width) {
    return <th {...restProps} />;
  }

  return (
    <Resizable
      width={width}
      height={0}
      handle={
        <span
          className="react-resizable-handle"
          onClick={(e) => {
            e.stopPropagation();
          }}
        />
      }
      onResize={onResize}
      draggableOpts={{ enableUserSelectHack: false }}
    >
      <th {...restProps} />
    </Resizable>
  );
};

interface BaseTableProps extends Omit<TableProps<any>, 'columns'> {
  columns: BaseColumn[];
}

const BaseTable: React.FC<BaseTableProps> = ({ columns: initialColumns, ...props }) => {
  const [columns, setColumns] = useState(initialColumns);

  const handleResize = (index) => (e, { size }) => {
    const nextColumns = [...columns];
    nextColumns[index] = {
      ...nextColumns[index],
      width: size.width,
    };
    setColumns(nextColumns);
  };

  const resizableColumns = columns.map((col, index) => ({
    ...col,
    onHeaderCell: (column: any) => ({
      width: column.width,
      onResize: handleResize(index),
    }),
  }));

  const components = {
    header: {
      cell: ResizableTitle,
    },
  };

  return (
    <div className="base-table-wrapper">
      <Table
        {...props}
        components={components}
        columns={resizableColumns as any}
        className={`base-table ${props.className || ''}`}
        scroll={{ x: 'max-content' }}
      />
    </div>
  );
};

export default BaseTable;